package com.ist.viewpagerhelper.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

/**
 * Created by Administrator on 2017/10/21.
 */

public class LineIndecator extends LinearLayout {
    private static final String TAG = "zsr";
    private Path mPath;
    private Paint mPaint;
    private int mLineWidth;
    private int mLineHeight;
    private int mInitX; //刚开始横条的x坐标
    private int mCount = 3;
    private float mLineOffert = 1.0f/6; // 几分之几

    private int mLineTransX = 0; //移动的位置
    public LineIndecator(Context context) {
        this(context,null);
    }

    public LineIndecator(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LineIndecator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initData();

    }


    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.save();
        //偏移 canvas 的起始位置
        canvas.translate(mInitX + mLineTransX,getHeight()+1);
        canvas.drawPath(mPath,mPaint);

        canvas.restore();

        super.dispatchDraw(canvas);
    }

    private void initData() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setPathEffect(new CornerPathEffect(5));



    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mLineWidth = (int) (w/2*mLineOffert);
        mLineHeight = 10;

        mInitX = (w/mCount - mLineWidth)/2;

        Log.d(TAG, "onSizeChanged: "+w+" "+mLineWidth+" "+mInitX);

        // 绘制长线
        mPath = new Path();

        // mPath.addRect(mInitX,h - mLineHeight,mLineWidth,h, Path.Direction.CW);
        mPath.moveTo(0,0);
        mPath.lineTo(mLineWidth,0);
        mPath.lineTo(mLineWidth/2,-mLineWidth/2+20);
        mPath.close();

    }

    public void onScroll(int position, float offset) {
        Log.d(TAG, "onScroll: "+offset);
        int tabWidth = getWidth()/mCount;
        mLineTransX = (int) (tabWidth*position + tabWidth*offset);
        invalidate();
    }
}
